package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.PropertiesUtil
import cn.com.elite.SendBatchMail
import cn.com.elite.Util
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.velocity.Template
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.VelocityEngine

import java.text.SimpleDateFormat
import java.time.LocalDate

/**
 *
 * @Title: cn.com.callback-autoEmailGroupSendTask
 * @Description:ngsapitask-ms 自动任务
 * @Author: hucf
 * @Date 2023/7/13 17:21
 *
 */
class autoEmailGroupSendTask implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoEmailGroupSendTask.class);
    //数据源
    static String dataSource = "dataSource";
    private static final String CHARSET = "utf-8"; //设置字符集
    private static final Integer TIME_OUT = 100000; //设置请求超时时间
    private static final Integer ENABLE_SSL_FLAG = 0;
    private static String mail_downLoadUrl;


    @Override
    void doCallBack(EliteBean eliteBean, String s, Map map, String s1) {
        // 定义发送批量邮件参数--EX
        List<Map<String, Object>> exSendList = new ArrayList<Map<String, Object>>();

        // 定义发送批量邮件参数--UM
        List<Map<String, Object>> umSendList = new ArrayList<Map<String, Object>>();

        List attachDeleteList = new ArrayList();
        String pdfTempPath = "";

        //获取配置文件信息
        PropertiesUtil properties = new PropertiesUtil();
        String emailDir = properties.readValue("emaildir");

        String azBaseurl = properties.readValue("azBaseurl");
        // exchange账号配置
        String exHost = properties.readValue("ex_host");
        String exSendAddress = properties.readValue("ex_username");
        String exUserName = properties.readValue("ex_username");
        String exPassword = properties.readValue("ex_password");
        String pdfChangeUrl = properties.readValue("crmip");
        //邮件正文写到本地的临时目录
        String mail_HtmlPath = properties.readValue("mail_HtmlPath");

        //月初文件下载本地地址
        mail_downLoadUrl = properties.readValue("mail_downLoadUrl");

        //邮件正文html文件所在服务器访问URL
        String mail_htmlFileURL = properties.readValue("mail_htmlFileURL");

        //获取页面访问地址
        String paperPath = properties.readValue("paperPath");

        //获取电子章路径
        String ElectronicSealPath = properties.readValue("ElectronicSealPath");

        // uMail账号配置
        String umHost = properties.readValue("um_host");
        String umSendAddress = properties.readValue("um_username");
        String umUserName = properties.readValue("um_username");
        String umPassword = properties.readValue("um_password");

        Integer port = 25;
        List emailGroupSendTaskList = null;
        String startTime = "";
        String endTime = "";
        String fileName = "accountno.html";
        // 获取配置的服务器访问URL
        String ccserverip = properties.readValue("ccserverip");
        try {
            LocalDate currentDate = LocalDate.now();
            JSONObject emailAccountJson = new JSONObject();
            //创建接口调用请求头接口
            Map<String, String> headerParams = new HashMap<String, String>();
            headerParams.put("Content-Type", "application/json");
            //拼接电子对账单数据
            String getEmailDetailSql = "select rec_guid as REC_GUID,SK_INVPTY as CUSTOMER_ID,RECEVICE_EMAIL,CARBON,time_interval as TIME_INTERVAL from email_group_info where status = 1 and send_status = 0 and expect_time < (sysdate + 0.001)";
            List emailDetailList = eliteBean.chaxun_sql(getEmailDetailSql, dataSource);
            log.debug("emailDetailList:" + emailDetailList.size());
            if (emailDetailList.size() > 0) {
                JSONArray emailDetailArray = JSONArray.fromObject(emailDetailList);
                for (int z = 0; z < emailDetailArray.size(); z++) {
                    emailAccountJson.put("year", currentDate.getYear());
                    emailAccountJson.put("month", currentDate.getMonthValue());
                    emailAccountJson.put("day", currentDate.getDayOfMonth());
                    Integer flag = 0;
                    String courtesy = "";
                    JSONObject emailDetailObject = emailDetailArray.get(z);
                    log.debug("emailDetailObject:" + emailDetailObject.toString());
                    String customerId = emailDetailObject.getString("CUSTOMER_ID");
                    String rec_guid = emailDetailObject.getString("REC_GUID");
                    String receiveEmail = emailDetailObject.getString("RECEVICE_EMAIL");
                    String carbon = emailDetailObject.getString("CARBON");
                    Integer timeInterval = emailDetailObject.getInt("TIME_INTERVAL");
                    log.debug("timeInterval:" + timeInterval);
                    switch (timeInterval) {
                        case 1: //上月
                            Map<String, String> lastMonthMap = getLastStartOrEndDayOfMonth();
                            startTime = lastMonthMap.get("beginTime");
                            endTime = lastMonthMap.get("endTime");
                            emailAccountJson.put("sectiontype", "上月");
                            break;
                        case 2: //上季度
                            Map<String, String> lastQuarterMap = getLastStartOrEndDayOfQuarter();
                            startTime = lastQuarterMap.get("beginTime");
                            endTime = lastQuarterMap.get("endTime");
                            emailAccountJson.put("sectiontype", "上季度");
                            break;
                        case 3: //上年度
                            Map<String, String> lastAnnualMap = getLastStartOrEndDayOfYear();
                            startTime = lastAnnualMap.get("beginTime");
                            endTime = lastAnnualMap.get("endTime");
                            emailAccountJson.put("sectiontype", "上年度");
                            break;
                        case 4: //本月
                            Map<String, String> lastYearMap = getStartOrEndDayOfMonth();
                            startTime = lastYearMap.get("beginTime");
                            endTime = lastYearMap.get("endTime");
                            emailAccountJson.put("sectiontype", "本月");
                            break;
                    }
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
                    SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
                    String startTime2 = sdf3.format(sdf2.parse(startTime));
                    String endTime2 = sdf3.format(sdf2.parse(endTime));
                    String startTime3 = sdf2.format(sdf2.parse(startTime));
                    String endTime3 = sdf2.format(sdf2.parse(endTime));
                    log.debug("startTime2:" + startTime2 + "endTime2:" + endTime2);
                    emailAccountJson.put("starttime_s", startTime2);
                    emailAccountJson.put("endtime_s", endTime2);
                    emailAccountJson.put("starttime", startTime2);
                    emailAccountJson.put("endtime", endTime2);
                    //调用客户信息接口
                    customerInfo(customerId, endTime3, startTime3, azBaseurl, headerParams, courtesy, flag, emailAccountJson);
                    //调用客户信息持有明细接口
                    holdInfo(customerId, endTime3, azBaseurl, headerParams, flag, emailAccountJson);
                    //调用交易明细接口
                    transaction(customerId, endTime3, startTime3, azBaseurl, headerParams, flag, emailAccountJson);
                    //调用分红明细按钮
                    bonus(customerId, endTime3, startTime3, azBaseurl, headerParams, flag, emailAccountJson);
                    log.debug("emailAccountJson:" + emailAccountJson.toString());

                    // 检查获取服务器文件存储路径
                    try {
                        String filePath = properties.readValue("mail_downLoadUrl") + fileName;
                        log.info("EmailCreateTask 模板文件路径:" + filePath);

                        File templateFile = new File(filePath);
                        if (true) {
                            // 拼接模板文件下载请求URL
                            String httpurl = "http://" + ccserverip + "/ngs/fs/get?file=emailtemplate/" + fileName + "&d=true";
                            log.info("EmailCreateTask 模板文件下载请求URL:" + httpurl);

                            // 执行下载操作
                            boolean flag1 = Util.httpDownLoadFile(httpurl, filePath, 10000);

                            // 打印文件处理下载结果
                            if (flag1) {
                                log.info("EmailCreateTask 获取模板文件成功:" + flag);
                            } else {
                                log.warn("EmailCreateTask 获取模板文件警告！请求flag:" + flag);
                            }
                        }
                    } catch (Exception e) {
                        log.error("EmailCreateTask 检查获取服务器文件存储路径Exception:", e)
                    }
                    String content = getMergeContent(JSONObject.fromObject(emailAccountJson).toString(), fileName, "UTF-8");
                    // 将邮件正文写到本地
                    String htmlName = KHUtil.getRandomString(6);
                    String htmlPath = paperPath + htmlName + ".html";
                    String htmlFile = mail_HtmlPath + "/" + htmlName + ".html";
                    attachDeleteList.add(htmlFile);
                    boolean bool = writeFile(content, htmlFile);
                    log.debug("将邮件正文写到本地 是否写入成功：" + bool);

                    //拼接执行路径
                    String zxRoute = mail_htmlFileURL + "/" + htmlName + ".html";
                    //拼接生成PDF文件json格式报文
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ismerge", 1);
                    jsonObject.put("ismark", "1");//是否生成电子章，0不生成，1生成
                    JSONObject markinfo = new JSONObject();
                    markinfo.put("markpic", ElectronicSealPath);//电子章路径
                    markinfo.put("x_axis", 400);//电子章x轴位置
                    markinfo.put("y_axis", 100);//电子章y轴位置
                    markinfo.put("zoom", 25);//像素
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("id", "");
                    jsonObject1.put("url", zxRoute);
                    jsonArray.add(jsonObject1);
                    jsonObject.put("markinfo", markinfo);
                    jsonObject.put("value", jsonArray);
                    jsonObject.put("isBatchEmail", 1);//邮件批量标识
                    log.debug("调用转换pdf接口请求报文：" + jsonObject.toString());

                    //调用生成pdf文件接口
                    String PDFUrl = pdfChangeUrl + "apiPDFDeal";
                    String doPostResult = Util.doHttpPost(PDFUrl, jsonObject.toString(), "UTF-8", 120000, 0);
                    log.debug("pdf转换返回报文：" + doPostResult.toString());
                    JSONObject doResultJson = JSONObject.fromObject(doPostResult.toString());
                    String pdfMergePath = doResultJson.getString("value");

                    // 获取PDF文件名和文件路径KHUtil.getRandomString(6)
                    String pdfFileName = pdfMergePath.substring(pdfMergePath.lastIndexOf("/") + 1);
                    String pdfFilePath = pdfMergePath.replace("/" + pdfFileName, "");
                    String newPDFFileName = "民生加银机构月度对账单" + Util.getNowString("yyyyMMddHHmmss") + "-" + KHUtil.getRandomString(6) + ".pdf";
                    String newPDFFilePath = pdfFilePath + "/" + newPDFFileName;
                    log.debug("pdf存放地址：" + newPDFFilePath);
                    boolean reName = Util.renameFile(pdfMergePath, newPDFFileName);
                    String ATTACHMENT_GUID = UUID.randomUUID().toString();
                    String ATTACHMENT_NAME = "对账单/资产证明模板";
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String curTime = simpleFormat.format(new Date());
                    String fwUrl = "http://" + ccserverip + "/ngs/fs/get?file=pdf/dzd/" + curTime + "/" + newPDFFileName;
                    eliteBean.update("update email_group_info set ATTACHMENT_GUID='" + ATTACHMENT_GUID + "',path='" + fwUrl + "',pdf_path = '"+newPDFFilePath+"',send_status = 1 where rec_guid='" + rec_guid + "'", dataSource);
                    eliteBean.update("update email_group_send_task set ATTACHMENT_GUID='" + ATTACHMENT_GUID + "' where sk_invpty='" + customerId + "' and email = '" + receiveEmail + "' and carbon = '" + carbon + "'", dataSource);
                    int recCount = eliteBean.chaxun_sql("select count(1) CON from email_group_attachment where rec_guid = '" + rec_guid + "'", dataSource)[0].getAt("CON");
                    log.debug("recCount:" + recCount);
                    if (recCount > 0) {
                        eliteBean.update("update email_group_attachment set attachment_path = '" + newPDFFilePath + "',attachment_guid = '" + rec_guid + "'  where rec_guid = '" + rec_guid + "'", dataSource);
                    } else {
                        eliteBean.update("insert into email_group_attachment(rec_guid,attachment_guid,attachment_name,attachment_path,createddate,createdby) values('" + rec_guid + "','" + ATTACHMENT_GUID + "','" + ATTACHMENT_NAME + "','" + newPDFFilePath + "',sysdate,'SELITE')", dataSource);
                    }
                }
            }
            //获取分组邮件批量待发任务
            String getEmailGroupSendTask = '''select t.rec_guid,
                                               t.batch_id,
                                               t.subject,
                                               t.email,
                                               t.carbon,
                                               t.content,
                                               t.expectedstartdate,
                                               t.trialcount,
                                               t.trialcountlimit,
                                               t.pie,
                                               t.sk_invpty,
                                               t.invpty_name,
                                               t.content_type,
                                               t.pdf_path as PDF_PATH
                                          from email_group_send_task t
                                         where t.expectedstartdate < sysdate
                                           and t.trialcount < trialcountlimit
                                           and t.state = 0
                                         order by t.trialcount, t.priority''';
            emailGroupSendTaskList = eliteBean.chaxun_sql(getEmailGroupSendTask, dataSource);
            log.debug("待发送数据：" + emailGroupSendTaskList.size());
            try {
                if (emailGroupSendTaskList.size() > 0) {
                    //将集合数据转换为JSON
                    JSONArray emailJson = JSONArray.fromObject(emailGroupSendTaskList);
                    log.debug("待发送数据JSON：" + emailJson.size());
                    //循环处理分组邮件批量待发任务
                    for (int i = 0; i < emailJson.size(); i++) {
                        Map<String, Object> receviceMap = new HashMap<String, Object>();
                        //附件集合
                        List attachmentList = new ArrayList();
                        JSONObject emailObject = emailJson.get(i);
                        String recGuid = emailObject.getString("REC_GUID");
                        //获取批次号
                        String batchId = emailObject.getString("BATCH_ID");
                        //获取邮件主题
                        String subject = emailObject.getString("SUBJECT");
                        //获取接收邮箱
                        String email = emailObject.getString("EMAIL");
                        //获取邮件抄送
                        String carbon = emailObject.getString("CARBON");
                        log.debug("抄送邮箱：" + carbon);
                        //获取邮件正文
                        String contents = emailObject.getString("CONTENT");
                        //获取邮件发送尝试次数
                        Integer trialCount = emailObject.getInt("TRIALCOUNT");
                        //获取邮件发送最大尝试次数
                        Integer trialCountLimit = emailObject.getInt("TRIALCOUNTLIMIT");
                        //获取邮件发送通道
                        Integer pie = emailObject.getInt("PIE");
                        log.debug("发送通道：" + pie);
                        //获取客户编号
                        String customerIds = emailObject.getString("SK_INVPTY");
                        //获取客户姓名
                        String customerName = emailObject.getString("INVPTY_NAME");
                        //获取正文类型
                        String contentType = emailObject.getString("CONTENT_TYPE");
                        //获取附件路径
                        String path = emailObject.getString("PDF_PATH");
                        // 添加邮件对应的附件
                        attachmentList.add(path);
                        //生成邮件临时文件
                        String emailpath = emailDir + Util.getNowString("yyyy-MM-dd") + "/" + recGuid + ".eml";
                        def relativepath = "/email/" + Util.getNowString("yyyy-MM-dd") + "/" + recGuid + ".eml";
                        log.debug("处理待发送任务[" + i + "]:sk_invpty：" + customerIds + ",invpty_name：" + customerName);
                        //加入发送列表
                        receviceMap.put("rec_guid", recGuid);
                        receviceMap.put("receviceAddress", email);
                        receviceMap.put("subject", subject);
                        receviceMap.put("content", contents);
                        receviceMap.put("emlFilePath", emailpath);
                        receviceMap.put("attachmentList", attachmentList);
                        log.debug("抄送校验判断：" + !carbon.equals("") && !carbon.isEmpty() && carbon != null);
                        if(!carbon.equals("") && !carbon.isEmpty() && carbon != null){
                            receviceMap.put("ccUser", carbon);
                        }
                        receviceMap.put("batch_id", batchId);
                        receviceMap.put("contenttype", contentType);
                        receviceMap.put("relativepath", relativepath);
                        receviceMap.put("trialcount", trialCount);
                        receviceMap.put("trialcountlimit", trialCountLimit);

                        receviceMap.put("sendResult", false);
                        receviceMap.put("attachResult", false);
                        if (pie == 1) {
                            receviceMap.put("pipe", pie);
                            // 将这封待发送任务Map插入List
                            exSendList.add(receviceMap);
                            log.debug("Exchange待发送任务Map插入List[" + i + "]-Exchange Num:" + exSendList.size());
                        } else {
                            pie = 2;
                            receviceMap.put("pipe", pie);
                            // 将这封待发送任务Map插入List
                            umSendList.add(receviceMap);
                            log.debug("UMail待发送任务Map插入List[" + i + "]-UMail Num:" + umSendList.size());
                        }
                    }
                }
            } catch (Exception e) {
                log.error("处理分组邮件批量待发任务数据异常：" + e.getMessage());
            }
            try {
                // 调用发送批量邮件--EX
                if (exSendList.size() > 0) {
                    log.debug("Exchange调用发送批量邮件--Num:" + exSendList.size());
                    // 调用发送批量邮件
                    callSendDeal(eliteBean, exHost, port, exSendAddress, exUserName, exPassword, exSendList, emailGroupSendTaskList.size());
                    log.debug("EX-邮件发送成功");
                } else {
                    log.debug("Exchange停止调用发送邮件--Num:" + exSendList.size());
                }

                // 调用发送批量邮件--UM
                if (umSendList.size() > 0) {
                    log.debug("UMail调用发送批量邮件--Num:" + umSendList.size());
                    callSendDeal(eliteBean, umHost, port, umSendAddress, umUserName, umPassword, umSendList, emailGroupSendTaskList.size());
                    log.debug("UM-邮件发送成功");
                } else {
                    log.debug("UMail停止调用发送邮件--Num:" + umSendList.size());
                }
            } catch (Exception e) {
                log.error("调用批量发送方法异常：" + e.getMessage());
            }
        } catch (Exception e) {
            log.error("获取待发送任务SQL执行异常：" + e.getMessage());
        }
    }

    //批量发送方法
    public static callSendDeal(EliteBean eliteBean, String host, int port, String sendAddress, String username, String password, List<Map<String, Object>> sendList, Integer count) {

        // 定义接收批量邮件返回信息
        List resultList = new ArrayList();
        Map<String, Object> resultMap = new HashMap<String, Object>();

        try {
            resultList = SendBatchMail.goSendMail(host, port, sendAddress, username, password, sendList);
        } catch (Exception e) {
            log.error("邮件发送异常：" + e.getMessage());
        }

        log.debug("发送批量邮件返回结果 Num:" + resultList.size());

        try {
            // 处理返回数据
            for (int i = 0; i < resultList.size(); i++) {

                resultMap = (Map<String, Object>) resultList.get(i);

                String rec_guid = resultMap.get("rec_guid").toString();
                Integer trialCount = resultMap.get("trialcount");
                Integer trialCountLimit = resultMap.get("trialcountlimit");
                String relativePath = resultMap.get("relativepath").toString();
                Integer pipe = resultMap.get("pipe");
                String sendResult = resultMap.get("sendResult").toString();
                String attachResult = resultMap.get("attachResult").toString();
                String batchId = resultMap.get("batch_id").toString();

                if (sendResult.equals("true")) {
                    Integer[] dataResult = operatorEmailGroupSend(eliteBean, relativePath, sendAddress, pipe, sendResult, attachResult, rec_guid, count, batchId);
                    log.debug("批量处理数量：" + dataResult);
                } else {
                    if (trialCount == null) {
                        trialCount = 0;
                    }
                    if (trialCountLimit == null) {
                        trialCountLimit = 3;
                    }
                    trialCount++;
                    log.debug("trialCount:" + trialCount);
                    if (trialCount < trialCountLimit) {
                        eliteBean.update("update email_group_send_task set trialcount=trialcount+1 where rec_guid='" + rec_guid + "'", dataSource);
                    } else {
                        Integer[] dataResult = operatorEmailGroupSend(eliteBean, relativePath, sendAddress, pipe, sendResult, attachResult, rec_guid, count, batchId);
                        log.debug("批量处理数量：" + dataResult);
                    }
                }
                log.debug("发送结果详情[" + i + "]:Rec_Guid-" + rec_guid + " -sendResult:" + sendResult + " -attachResult:" + attachResult);
            }
        } catch (Exception e) {
            log.error("处理返回数据异常：" + e.getMessage());
        }
    }

    public static boolean writeFile(String fileContent, String FilePath) {

        long tstartTime, tendTime, startTime, endTime;

        tstartTime = System.currentTimeMillis();

        // 将文件内容写入本地服务器
        int i = 0;
        File dirAll = new File(FilePath);
        Writer fw = null;
        PrintWriter pw = null;
        startTime = System.currentTimeMillis();
        try {
            // 文件夹路径是否存在不存在则创建
            File dir = new File(dirAll.getParent());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 检查目标文件是否存在，不存在则创建
            if (!dirAll.exists()) {
                boolean flag = dirAll.createNewFile();
            }
            // 向目标文件中写入内容
            fw = new OutputStreamWriter(new FileOutputStream(FilePath), "UTF-8");
            pw = new PrintWriter(fw);
            pw.println(fileContent);
            pw.flush();
            log.debug("-File[" + i + "]写入文件完成...");

        } catch (Exception e) {
            log.error("-File[" + i + "]写入文件失败：", e);
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                log.warn("文件操作对象释放异常-", e);
            }
            endTime = System.currentTimeMillis();

            log.debug("-File[" + i + "]写入文件结束 Start time:" + startTime + "; End time:" + endTime + "; Run Time:" + (endTime - startTime) + "(ms)");

            i++;

        }

        tendTime = System.currentTimeMillis();
        log.debug("-File写入本地文件结束 End time:" + tendTime + "; Run Time:" + (tendTime - tstartTime) + "(ms)");

        return dirAll.exists();

    }

    //分组邮件发送后操作
    static Integer[] operatorEmailGroupSend(EliteBean eliteBean, String relativePath, String sendAddress, Integer pipe, String sendResult, String attachResult, String rec_guid, Integer count, String batchId) {
        String[] data = new String[7];
        Integer[] dataResult;
        Integer sendStatus = 2;
        if (sendResult.equals("true")) {
            sendStatus = 3;
        }else {
            sendStatus = 4;
        }
        try {
            /* String getBatchId = "";
             get = eliteBean.chaxun_sql("select to_char(sysdate,'yyyymmdd') as CURRENTTIME from dual", dataSource)[0].getAt("CURRENTTIME");
             getBatchId = "EM" + getBatchId + "9998";*/
            //记入documentOut发送记录表
            data[0] = '''insert into documentout
                                  (doctype,
                                   documentout_guid,
                                   status,
                                   trialcount,
                                   trialcountlimit,
                                   documentpath,
                                   comments,
                                   subject,
                                   documentfrom,
                                   documentto,
                                   attachflag,
                                   batch_id,
                                   pipe,
                                   sk_invpty,
                                   invpty_name,
                                   template_id,
                                   sendtype,
                                   expectedstartdate,
                                   createddate,
                                   STRINGFIELD1,
                                   STRINGFIELD2)
                                  select 2,
                                   sysguid,
                                   1,
                                   trialcount + 1,
                                   trialcountlimit,
                                   \'''' + relativePath + '''\',
                                   subject ,
                                   subject ,
                                   \'''' + sendAddress + '''\',
                                   email ,
                                   0 ,
                                   \'''' + batchId + '''\',
                                   ''' + pipe + ''' ,
                                   sk_invpty ,
                                   invpty_name ,
                                   template_id ,
                                   2 ,
                                   expectedstartdate ,
                                   sysdate ,
                                   \'''' + sendResult + '''\',
                                   \'''' + attachResult + '''\'
                                   from email_group_send_task
                                   where rec_guid =
                                   \'''' + rec_guid + '''\'''';

            data[1] = '''insert into documentout_his
                                  (doctype,
                                   documentout_guid,
                                   status,
                                   trialcount,
                                   trialcountlimit,
                                   documentpath,
                                   comments,
                                   subject,
                                   documentfrom,
                                   documentto,
                                   attachflag,
                                   batch_id,
                                   pipe,
                                   sk_invpty,
                                   invpty_name,
                                   template_id,
                                   sendtype,
                                   expectedstartdate,
                                   createddate,
                                   STRINGFIELD1,
                                   STRINGFIELD2)
                                  select 2,
                                   sysguid,
                                   1,
                                   trialcount + 1,
                                   trialcountlimit,
                                   \'''' + relativePath + '''\',
                                   subject ,
                                   subject ,
                                   \'''' + sendAddress + '''\',
                                   email ,
                                   0 ,
                                    \'''' + batchId + '''\',
                                   ''' + pipe + ''' ,
                                   sk_invpty ,
                                   invpty_name ,
                                   template_id ,
                                   2 ,
                                   expectedstartdate ,
                                   sysdate ,
                                   \'''' + sendResult + '''\',
                                   \'''' + attachResult + '''\'
                                   from email_group_send_task
                                   where rec_guid =
                                   \'''' + rec_guid + '''\'''';
            String getCustomerID = eliteBean.chaxun_sql("select sk_invpty from email_group_send_task where rec_guid='" + rec_guid + "'", dataSource)[0].getAt("sk_invpty");
            //将分组邮件维护发送状态更新且邮件状态更新为停用
            data[2] = "update email_group_info set send_status = " + sendStatus + ",status = 0,check_status = 1,modifieddate = sysdate,modifiedby = 'SELITE' where sk_invpty = '" + getCustomerID + "'";
            //更新批次表数量
            if (sendResult.equals("true")) {
                data[3] = "update email_send_batch_his set QUANTITYSUCC=QUANTITYSUCC+1,MESSAGES = MESSAGES + " + count + ",QUANTITYVALID = QUANTITYVALID + " + count + ",QUANTITYSENT= QUANTITYSENT + " + count + " where batch_id='" + batchId + "' and QUANTITYSUCC <=QUANTITYSENT";
                data[4] = "update email_send_batch set QUANTITYSUCC=QUANTITYSUCC+1,MESSAGES = MESSAGES + " + count + ",QUANTITYVALID = QUANTITYVALID + " + count + ",QUANTITYSENT= QUANTITYSENT + " + count + " where batch_id='" + batchId + "' and QUANTITYSUCC <=QUANTITYSENT";
            } else {
                data[3] = "update email_send_batch_his set QUANTITYFAIL=QUANTITYFAIL+1,MESSAGES = MESSAGES + " + count + ",QUANTITYVALID = QUANTITYVALID + " + count + ",QUANTITYSENT= QUANTITYSENT + " + count + " where batch_id='" + batchId + "' and QUANTITYFAIL <= QUANTITYSENT";
                data[4] = "update email_send_batch set QUANTITYSUCC=QUANTITYSUCC+1,MESSAGES = MESSAGES + " + count + ",QUANTITYVALID = QUANTITYVALID + " + count + ",QUANTITYSENT= QUANTITYSENT + " + count + " where batch_id='" + batchId + "' and QUANTITYSUCC <=QUANTITYSENT";
            }
            //删除待发任务
            data[5] = "delete from email_group_send_task where rec_guid='" + rec_guid + "'";
            //插入监控表
            data[6] = "insert into export (creategroup,createby,createdate,exporttype,customer_id,exportguid) values('29K76B','SELITE',sysdate,1,'"+ getCustomerID +"',sysguid)";
            dataResult = eliteBean.updateBatch(data, dataSource);
        } catch (Exception e) {
            log.error("数据执行异常：" + e.getMessage())
        }
        return dataResult;
    }

    /**
     * 功能描述: TODO 获取上个季度开始和结束时间
     */
    public static Map<String, String> getLastStartOrEndDayOfQuarter() {
        Map<String, String> dayMap = new HashMap<>(16);
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);

        // 计算上个季度的起始日期和结束日期
        calendar.add(Calendar.MONTH, -3);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date startDate = calendar.getTime();

        calendar.add(Calendar.MONTH, 3);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date endDate = calendar.getTime();

        // 格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String startDateStr = dateFormat.format(startDate);
        String endDateStr = dateFormat.format(endDate);
        dayMap.put("beginTime", startDateStr);
        dayMap.put("endTime", endDateStr);
        return dayMap;
    }

    /**
     * @Description TODO 获取去年的第一天或最后一天
     * @Param: [today, isFirst: true 表示开始时间，false表示结束时间]
     * @return: java.lang.String
     */
    public static Map<String, String> getLastStartOrEndDayOfYear() {
        Map<String, String> dayMap = new HashMap<>(16);
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        calendar.add(Calendar.YEAR, -1);
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 计算上个年度的起始日期和结束日期
        Date startDate = calendar.getTime();
        calendar.add(Calendar.YEAR, -1);
        calendar.set(Calendar.MONTH, Calendar.DECEMBER);
        calendar.set(Calendar.DATE, 31);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endDate = calendar.getTime();

        // 格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String startDateStr = dateFormat.format(startDate);
        String endDateStr = dateFormat.format(endDate);
        dayMap.put("beginTime", startDateStr);
        dayMap.put("endTime", endDateStr);
        return dayMap;
    }

    /**
     * 功能描述: 获取上月开始日期和结束日期
     */
    public static Map<String, String> getLastStartOrEndDayOfMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Map<String, String> dayMap = new HashMap<>(16);
        //获取当前日期
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        //设置为1号,当前日期既为本月第一天
        cal.set(Calendar.DAY_OF_MONTH, 1);
        String firstDay = sdf.format(cal.getTime());
        //获取前月的最后一天
        Calendar cale = Calendar.getInstance();
        //设置为1号,当前日期既为本月第一天
        cale.set(Calendar.DAY_OF_MONTH, 0);
        String lastDay = sdf.format(cale.getTime());
        dayMap.put("beginTime", firstDay);
        dayMap.put("endTime", lastDay);
        return dayMap;
    }

    /**
     * 功能描述: 获取本月的第一天或最后一天
     * @Param: [today, isFirst: true 表示开始时间，false表示结束时间]
     * @return: java.lang.String
     */
    public static Map<String, String> getStartOrEndDayOfMonth() {
        Map<String, String> dayMap = new HashMap<>(16);
        // 获取当前日期
        Date currentDate = new Date();
        // 创建Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 设置日期为当前日期
        calendar.setTime(currentDate);
        // 将日期设置为该月的第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // 获取本月的开始时间
        Date startTime = calendar.getTime();
        // 将日期设置为该月的最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        // 获取本月的结束时间
        Date endTime = calendar.getTime();

        // 格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String startDateStr = dateFormat.format(startTime);
        String endDateStr = dateFormat.format(endTime);
        dayMap.put("beginTime", startDateStr);
        dayMap.put("endTime", endDateStr);
        return dayMap;
    }

    public static String getCommaNum(String str) {
        String a = "";
        if (str.contains(String.valueOf('.'))) {
            int index = str.indexOf('.');
            a = str.substring(index, str.length());
            str = str.substring(0, index);
        }
        StringBuffer stringBuffer = new StringBuffer(str);
        for (int i = stringBuffer.length() - 3; i > 0; i -= 3) {
            stringBuffer.insert(i, ",");
        }
        if (a != "") {
            stringBuffer.append(a);
        }
        return stringBuffer.toString();
    }

    /**
     * 客户信息汇总
     * @param customerId
     * @param endTime
     * @param startTime
     * @param azBaseurl
     * @param headerParams
     * @param courtesy
     * @param flag
     * @param emailAccountJson
     */
    static void customerInfo(String customerId, String endTime, String startTime, String azBaseurl, Map<String, String> headerParams, String courtesy, Integer flag, JSONObject emailAccountJson) {
        try {
            JSONObject customerInfo = new JSONObject();
            customerInfo.put("custno", customerId);
            customerInfo.put("fundtype", 0);
            customerInfo.put("enddate", endTime);
            customerInfo.put("startdate", startTime);
            String customerInfoUrl = "http://" + azBaseurl + "/msjy/callcenter/v1/custinfo/total";
            //String customerInfoUrl = "http://" + azBaseurl + "/EliteGeneralHttpTask/GeneralService/customerInfo";
            log.debug("客户明细接口参数：" + customerInfo.toString());
            String customerInfoResult = Util.doHttpPostUseHead(customerInfoUrl, customerInfo.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headerParams);
            JSONObject customerInfoResultJson = JSONObject.fromObject(customerInfoResult);
            if (customerInfoResultJson.getJSONArray("results") != null && !customerInfoResultJson.getJSONArray("results").isEmpty()) {
                JSONArray infoResultArray = customerInfoResultJson.getJSONArray("results");
                if (customerInfoResultJson.getString("code") == "200" && infoResultArray.size() > 0) {
                    JSONObject infoObject = infoResultArray.get(0);
                    String customerName = infoObject.getString("custname");//客户名称
                    String email = infoObject.getString("email");//邮箱
                    String customerType = infoObject.getString("custtype");//客户类型（0：机构 1：个人 2：产品）
                    String customerNo = infoObject.getString("fundacco");//客户编号
                    String income = infoObject.getString("income");//持仓收益
                    String incomeAll = infoObject.getString("income_all");//当前累计收益
                    String capital = infoObject.getString("capital");//持有市值
                    String tradeCount = infoObject.getString("trade_count");//交易笔数
                    String balanceIn = infoObject.getString("balance_in");//投入金额
                    String incomeRange = infoObject.getString("income_range");//区间收益
                    if (customerType == "1") {
                        courtesy = courtesy + customerName + "先生/女士";
                    } else {
                        courtesy = customerName;
                    }
                    flag += 1;
                    emailAccountJson.put("fundaccount", customerNo);
                    emailAccountJson.put("capital", capital);
                    emailAccountJson.put("income", income);
                    emailAccountJson.put("income_all", incomeAll);
                    emailAccountJson.put("trade_count", tradeCount);
                    emailAccountJson.put("balance_in", balanceIn);
                    emailAccountJson.put("income_range", incomeRange);
                    emailAccountJson.put("customername", courtesy);
                }
            }
            emailAccountJson.put("flag", flag);
        } catch (Exception e) {
            log.error("客户信息汇总调用报错：" + e.getMessage());
        }
    }

    /**
     * 持有明细
     * @param customerId
     * @param endTime
     * @param azBaseurl
     * @param headerParams
     * @param flag
     * @param emailAccountJson
     */
    static void holdInfo(String customerId, String endTime, String azBaseurl, Map<String, String> headerParams, Integer flag, JSONObject emailAccountJson) {
        try {
            JSONObject holdInfo = new JSONObject();
            holdInfo.put("custno", customerId);
            holdInfo.put("fundtype", 0);
            holdInfo.put("enddate", endTime);
            holdInfo.put("is_hold", 1);
            String holdInfoUrl = "http://" + azBaseurl + "/msjy/callcenter/v1/hold/detail";
            //String holdInfoUrl = "http://" + azBaseurl + "/EliteGeneralHttpTask/GeneralService/holdInfo";
            log.debug("持有明细请求报文：" + holdInfo.toString());
            String holdInfoResult = Util.doHttpPostUseHead(holdInfoUrl, holdInfo.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headerParams);

            JSONObject holdInfoResultJson = JSONObject.fromObject(holdInfoResult);
            if (holdInfoResultJson.getJSONArray("results") != null && !holdInfoResultJson.getJSONArray("results").isEmpty()) {
                JSONArray holdInfoArray = holdInfoResultJson.getJSONArray("results");
                if (holdInfoResultJson.getString("code") == "200" && holdInfoArray.size() > 0) {
                    JSONObject jsonin = new JSONObject();
                    JSONArray arr = new JSONArray();
                    JSONArray arr1 = new JSONArray();
                    JSONArray arr2 = new JSONArray();
                    JSONArray arr3 = new JSONArray();
                    JSONArray arr4 = new JSONArray();
                    JSONArray arr5 = new JSONArray();
                    JSONArray arr6 = new JSONArray();
                    JSONArray arr7 = new JSONArray();
                    for (int x = 0; x < holdInfoArray.size(); x++) {
                        JSONObject holdInfoObject = holdInfoArray.get(x);
                        String fundClass = holdInfoObject.getString("fundclass");
                        //股票型
                        if (fundClass == "1") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr1.add(jsonin);
                            emailAccountJson.put("tabletotala1", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa1", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);
                        }
                        //混合型
                        if (fundClass == "2") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr2.add(jsonin);
                            emailAccountJson.put("tabletotala2", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa2", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                        //指数型
                        if (fundClass == "3") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr3.add(jsonin);
                            emailAccountJson.put("tabletotala3", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa3", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                        //FOF
                        if (fundClass == "4") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr4.add(jsonin);
                            emailAccountJson.put("tabletotala4", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa4", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                        //债券型
                        if (fundClass == "5") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr5.add(jsonin);
                            emailAccountJson.put("tabletotala5", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa5", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                        //货币型
                        if (fundClass == "6") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr6.add(jsonin);
                            emailAccountJson.put("tabletotala6", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa6", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                        //私募产品
                        if (fundClass == "7") {
                            jsonin.put("c0", holdInfoObject.getString("fundname"));
                            jsonin.put("c1", holdInfoObject.getString("fundcode"));
                            jsonin.put("c2", holdInfoObject.getString("share"));
                            jsonin.put("c3", holdInfoObject.getString("nav"));
                            jsonin.put("c4", holdInfoObject.getString("capital"));
                            jsonin.put("c5", holdInfoObject.getString("dividend_type"));
                            jsonin.put("c6", holdInfoObject.getString("agencyname"));
                            jsonin.put("c7", holdInfoObject.getString("fund_risk_level"));
                            arr7.add(jsonin);
                            emailAccountJson.put("tabletotala7", holdInfoObject.getString("fundtype_capital"));
                            emailAccountJson.put("ratioa7", Math.floor(holdInfoObject.getDouble("fundtype_rate") * 10000) / 100);

                        }
                    }
                    if (arr1.size() <= 0) {
                        emailAccountJson.put("displaya1", "none")
                    }
                    if (arr2.size() <= 0) {
                        emailAccountJson.put("displaya2", "none")
                    }
                    if (arr3.size() <= 0) {
                        emailAccountJson.put("displaya3", "none")
                    }
                    if (arr4.size() <= 0) {
                        emailAccountJson.put("displaya4", "none")
                    }
                    if (arr5.size() <= 0) {
                        emailAccountJson.put("displaya5", "none")
                    }
                    if (arr6.size() <= 0) {
                        emailAccountJson.put("displaya6", "none")
                    }
                    if (arr7.size() <= 0) {
                        emailAccountJson.put("displaya7", "none")
                    }

                    emailAccountJson.put("t_tablea1", arr1)
                    emailAccountJson.put("t_tablea2", arr2)
                    emailAccountJson.put("t_tablea3", arr3)
                    emailAccountJson.put("t_tablea4", arr4)
                    emailAccountJson.put("t_tablea5", arr5)
                    emailAccountJson.put("t_tablea6", arr6)
                    emailAccountJson.put("t_tablea7", arr7)
                    //监听累计
                    flag += 1;
                } else {
                    emailAccountJson.put("displaya1", "none");
                    emailAccountJson.put("displaya2", "none");
                    emailAccountJson.put("displaya3", "none");
                    emailAccountJson.put("displaya4", "none");
                    emailAccountJson.put("displaya5", "none");
                    emailAccountJson.put("displaya6", "none");
                    emailAccountJson.put("displaya7", "none");
                    flag += 1;
                }
            } else {
                emailAccountJson.put("displaya1", "none");
                emailAccountJson.put("displaya2", "none");
                emailAccountJson.put("displaya3", "none");
                emailAccountJson.put("displaya4", "none");
                emailAccountJson.put("displaya5", "none");
                emailAccountJson.put("displaya6", "none");
                emailAccountJson.put("displaya7", "none");
                flag += 1;
            }
            emailAccountJson.put("flag", flag);
        } catch (Exception e) {
            log.error("持有明细调用报错：" + e.getMessage());
        }
    }

    /**
     * 交易明细
     * @param customerId
     * @param endTime
     * @param startTime
     * @param azBaseurl
     * @param headerParams
     * @param flag
     * @param emailAccountJson
     */
    static void transaction(String customerId, String endTime, String startTime, String azBaseurl, Map<String, String> headerParams, Integer flag, JSONObject emailAccountJson) {
        try {
            JSONObject transactionInfo = new JSONObject();
            transactionInfo.put("custno", customerId);
            transactionInfo.put("fundtype", 0);
            transactionInfo.put("enddate", endTime);
            transactionInfo.put("startdate", startTime);
            String transactionInfoUrl = "http://" + azBaseurl + "/msjy/callcenter/v1/trade/detail";
            //String transactionInfoUrl = "http://" + azBaseurl + "/EliteGeneralHttpTask/GeneralService/transactionInfo";
            log.debug("交易明细请求报文：" + transactionInfo.toString());
            String transactionInfoResult = Util.doHttpPostUseHead(transactionInfoUrl, transactionInfo.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headerParams);

            JSONObject transactionInfoResultJson = JSONObject.fromObject(transactionInfoResult);
            if (transactionInfoResultJson.getJSONArray("results") != null && !transactionInfoResultJson.getJSONArray("results").isEmpty()) {
                JSONArray transactionInfoArray = transactionInfoResultJson.getJSONArray("results");
                String[][] resultArr1 = new String[transactionInfoArray.size()][10];
                if (transactionInfoResultJson.getString("code") == "200" && transactionInfoArray.size() > 0) {
                    for (int y = 0; y < transactionInfoArray.size(); y++) {
                        JSONObject transactionInfoObject = transactionInfoArray.get(y);
                        resultArr1[y][0] = transactionInfoObject.getString("requestdate");
                        resultArr1[y][1] = transactionInfoObject.getString("confirmdate");
                        resultArr1[y][2] = transactionInfoObject.getString("fundname");
                        resultArr1[y][3] = transactionInfoObject.getString("fundcode");
                        resultArr1[y][4] = transactionInfoObject.getString("agencyname");
                        resultArr1[y][5] = transactionInfoObject.getString("businname");
                        resultArr1[y][6] = transactionInfoObject.getString("confirmbalance");
                        resultArr1[y][7] = transactionInfoObject.getString("confirmshare");
                        resultArr1[y][8] = transactionInfoObject.getString("nav");
                        resultArr1[y][9] = transactionInfoObject.getString("tradefee");
                    }
                    emailAccountJson.put("t_tableb", resultArr1);
                    int arr1Count;
                    for (int w = 0; w < resultArr1[0].length; w++) {
                        log.debug("数组是否为空：" + (resultArr1[0][w] == null));
                        log.debug("小数组数据：" + resultArr1[0][w]);
                        if (resultArr1[0][w] != null) {
                            arr1Count++;
                        }
                    }

                    //控制对账单-交易明细 显隐
                    if (arr1Count > 0) {
                        emailAccountJson.put("displayb", "");
                    } else {
                        emailAccountJson.put("displayb", "none");
                    }
                    //监听累计
                    flag += 1;
                } else {
                    emailAccountJson.put("displayb", "none");
                    //监听累计
                    flag += 1;
                }
            } else {
                String[][] resultArr1 = new String[0][10];
                emailAccountJson.put("t_tableb", resultArr1);
            }
            emailAccountJson.put("flag", flag);
        } catch (Exception e) {
            log.error("交易明细调用报错：" + e.getMessage());
        }
    }

    /**
     * 分红明细
     * @param customerId
     * @param endTime
     * @param startTime
     * @param azBaseurl
     * @param headerParams
     * @param flag
     * @param emailAccountJson
     */
    static void bonus(String customerId, String endTime, String startTime, String azBaseurl, Map<String, String> headerParams, Integer flag, JSONObject emailAccountJson) {
        try {
            JSONObject bonusInfo = new JSONObject();
            bonusInfo.put("custno", customerId);
            bonusInfo.put("fundtype", 0);
            bonusInfo.put("enddate", endTime);
            bonusInfo.put("startdate", startTime);
            String bonusInfoUrl = "http://" + azBaseurl + "/msjy/callcenter/v1/dividend/detail";
            //String bonusInfoUrl = "http://" + azBaseurl + "/EliteGeneralHttpTask/GeneralService/bonusInfo";
            log.debug("分红明细请求报文：" + bonusInfo.toString());
            String bonusInfoResult = Util.doHttpPostUseHead(bonusInfoUrl, bonusInfo.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headerParams);

            JSONObject bonusInfoResultJson = JSONObject.fromObject(bonusInfoResult);
            if (bonusInfoResultJson.getJSONArray("results") != null && !bonusInfoResultJson.getJSONArray("results").isEmpty()) {
                JSONArray bonusInfoArray = bonusInfoResultJson.getJSONArray("results");
                String[][] resultArr = new String[bonusInfoArray.size()][9];
                if (bonusInfoResultJson.getString("code") == "200" && bonusInfoArray.size() > 0) {
                    for (int r = 0; r < bonusInfoArray.size(); r++) {
                        JSONObject bonusInfoObject = bonusInfoArray.get(r);
                        resultArr[r][0] = bonusInfoObject.getString("registerdate");
                        resultArr[r][1] = bonusInfoObject.getString("fundname");
                        resultArr[r][2] = bonusInfoObject.getString("agencyname");
                        resultArr[r][3] = bonusInfoObject.getString("dividendtype");
                        resultArr[r][4] = bonusInfoObject.getString("distributedate");
                        resultArr[r][5] = bonusInfoObject.getString("share_base");
                        resultArr[r][6] = bonusInfoObject.getString("balance_real");
                        resultArr[r][7] = bonusInfoObject.getString("nav_reinvest");
                        resultArr[r][8] = bonusInfoObject.getString("share_reinvest");
                    }
                    emailAccountJson.put("t_tablec", resultArr);
                    int arr1Count;
                    for (int w = 0; w < resultArr[0].length; w++) {
                        log.debug("数组是否为空：" + (resultArr[0][w] == null));
                        log.debug("小数组数据：" + resultArr[0][w]);
                        if (resultArr[0][w] != null) {
                            arr1Count++;
                        }
                    }

                    //控制对账单-交易明细 显隐
                    if (arr1Count > 0) {
                        emailAccountJson.put("displayc", "");
                    } else {
                        emailAccountJson.put("displayc", "none");
                    }
                    //监听累计
                    flag += 1;
                } else {
                    emailAccountJson.put("displayc", "none");
                    //监听累计
                    flag += 1;
                }
            } else {
                String[][] resultArr = new String[0][9];
                emailAccountJson.put("t_tablec", resultArr);
            }
            emailAccountJson.put("flag", flag);
        } catch (Exception e) {
            log.error("分红明细调用报错：" + e.getMessage());
        }
    }

    public static String getMergeContent(String contentJson, String filename, String charset) throws Exception {
        VelocityEngine ve = new VelocityEngine();
        Properties p = new Properties();
        p.setProperty("file.resource.loader.path", mail_downLoadUrl);
        ve.init(p);
        new JSONObject();
        JSONObject jsonObj = JSONObject.fromObject(contentJson);
        VelocityContext context = new VelocityContext();
        context.put("dynamicPage", jsonObj);
        StringWriter writer = new StringWriter();
        Template t = ve.getTemplate(filename, charset);
        t.merge(context, writer);
        String content = writer.toString();
        return content;
    }
}